package com.qdxwx.common.utils;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
public class TKCookie {
    /**
     * 获取cookies
     *
     * @param request   HttpServletRequest
     * @param cacheName cacheName
     * @return String
     */
    public static String get(HttpServletRequest request, String cacheName) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cacheName.equalsIgnoreCase(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void set(HttpServletResponse response, String cacheName, String cacheValue, int days) {
        set(response, cacheName, cacheValue, 30, null);
    }

    public static void set(HttpServletResponse response, String cacheName, String cacheValue, String domain) {
        set(response, cacheName, cacheValue, 30, domain);
    }

    public static void set(HttpServletResponse response, String cacheName, String cacheValue, int days, String domain) {
        Cookie cookie = new Cookie(cacheName, cacheValue);
        if (domain != null) {
            cookie.setDomain(domain);
        }
        cookie.setMaxAge(60 * 60 * 24 * days);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static void delete(HttpServletResponse response, String cacheName) {
        delete(response, cacheName, null);
    }

    public static void delete(HttpServletResponse response, String cacheName, String domain) {
        Cookie cookie = new Cookie(cacheName, null);
        if (domain != null) {
            cookie.setDomain(domain);
        }
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static String getDomain(HttpServletRequest request) {
        String serverName = request.getServerName().toLowerCase();
        if (serverName.contains("youtike.com")) {
            return "youtike.com";
        } else if (serverName.contains("qdxwx.com")) {
            return "qdxwx.com";
        } else if (serverName.contains("qidianxue.cn")) {
            return "qidianxue.cn";
        } else {
            return serverName;
        }
    }

    public static String getLoginId(HttpServletRequest request) {
        return get(request, "loginId");
    }

    public static void setLoginId(HttpServletResponse response, String loginId) {
        set(response, "loginId", loginId, null);
    }
}
